#include "test_ioqueue.h"

#include "pjlib.h"


static void on_ioqueue_read(pj_ioqueue_key_t *key,
                     pj_ioqueue_op_key_t *op_key,
                     pj_ssize_t bytes_read)
{
    PJ_LOG(3,("","on read"));

}

static void on_ioqueue_write(pj_ioqueue_key_t *key,
                      pj_ioqueue_op_key_t *op_key,
                      pj_ssize_t bytes_written)
{
    PJ_LOG(3,("","on write"));

}

static void on_ioqueue_accept(pj_ioqueue_key_t *key,
                       pj_ioqueue_op_key_t *op_key,
                       pj_sock_t sock,
                       int status)
{
    PJ_LOG(3,("","on accept"));

}

static void on_ioqueue_connect(pj_ioqueue_key_t *key, int status)
{
    PJ_LOG(3,("","on connect"));
}

void test_ioqueue()
{
    pj_status_t res;
    pj_sock_t client;
    res = pj_sock_socket( pj_AF_INET(), pj_SOCK_STREAM(), 0, &client );
    if( res!= PJ_SUCCESS )
    {
        PJ_LOG(3, ("test_ioqueue", "create socket fail"));
    }

    pj_str_t ipstring = pj_str("localhost");
    pj_sockaddr server_address;
    res = pj_sockaddr_init(pj_AF_INET(), &server_address, &ipstring , 800 );
    if( res!= PJ_SUCCESS )
    {
        PJ_LOG(3, ("test_ioqueue", "init socket address fail"));
    }

    pj_caching_pool cp;
    pj_caching_pool_init( &cp, NULL, 1024*1024 );
    pj_ioqueue_key_t *ckey;
    
    pj_ioqueue_t * p_ioq;
    pj_pool_t * mp = pj_pool_create( &cp.factory, "shibo", 1024,1024, NULL ); 

    res = pj_ioqueue_create(mp, 10,&p_ioq );
    if( res!= PJ_SUCCESS )
    {
        PJ_LOG(3,("test_ioqueue"," create ioqueue fail") );
    }

    pj_ioqueue_callback cb =
    {
       &on_ioqueue_read,
       &on_ioqueue_write,
       &on_ioqueue_accept,
       &on_ioqueue_connect
    };

    res = pj_ioqueue_register_sock(mp, p_ioq, client, NULL, &cb , &ckey );
    if( res != PJ_SUCCESS )
    {
        PJ_LOG(3, ("","register fail"));
    }
    res = pj_ioqueue_connect( ckey, &(server_address.ipv4), sizeof(server_address.ipv4) );
    if( res != PJ_SUCCESS && res!=PJ_EPENDING )
    {
        PJ_LOG(3, ("","connect fail"));
    }
    if(res==PJ_EPENDING )
    {
        PJ_LOG(3, ("","pending"));
    }

    pj_time_val timeout;
    timeout.sec = 1;
    timeout.msec = 0;

    char buff[100];
    pj_ssize_t buff_length = 100;
    pj_ioqueue_op_key_t opk;
    while(1)
    {
        pj_ioqueue_recv( ckey, &opk, buff, &buff_length,0 );
        pj_ioqueue_poll( p_ioq, &timeout);
    }

}